package cn.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读读并发 读写 写写互斥(表示线程状态并发或者互斥)
 */
public class ReadWriteLock {
    public static void main(String[] args) {
        Container data=new Container();
        new Thread(()->{

            try {
                Thread.sleep(1000);
                data.read();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            data.write();
        }).start();
    }
}
@Slf4j
class Container{
    private Object data;
    private ReentrantReadWriteLock rw=new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock=rw.readLock();//读锁
    private ReentrantReadWriteLock.WriteLock writeLock=rw.writeLock();//写锁
    public Object read(){
        readLock.lock();
        try {
            log.info("数据读取中");
            return this.data;
        }
        finally {
            readLock.unlock();
        }
    }
    public void write(){
        writeLock.lock();
        try {
            log.info("数据写出中");
            this.data = data;
        }finally {
            writeLock.unlock();
        }
    }
}